﻿using Microsoft.SharePoint;
using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using System.Data;
namespace Portal
{
    [ToolboxItemAttribute(false)]
    public partial class MyAnnouncements : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public MyAnnouncements()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Web;
            SPView spView = web.Lists["UserAnnouncements"].Views["MyUserAnnouncements"];
            SPQuery spQuery = new SPQuery(spView);
            
            spQuery.ViewFields = @"<FieldRef Name='ID' /><FieldRef Name='LastAnnouncementRead' />
                                    <FieldRef Name='User' />";
            SPListItemCollection annItems = web.Lists["UserAnnouncements"].GetItems(spQuery);
            
            if (annItems.Count > 0)
            {
                //var last annItems[0]["LastAnnouncementRead"]
            }
            else
            {
                SPListItem newUser = web.GetList("UserAnnouncements").AddItem();
                newUser["User"] = SPContext.Current.Web.CurrentUser;                
                newUser.Update();
            }

            if (annItems.Count > 0)
            {
                var announcementItems = from anItem in annItems.GetDataTable().AsEnumerable()
                                          select new
                                          {
                                              AnnouncementTitle = anItem["Title"].ToString(),
                                              AnnouncementDescription=anItem["AnnouncementDescription"].ToString(),
                                              AnnouncementID = anItem["ID"].ToString()


                                          };

                dlMyAnnouncements.DataSource = announcementItems.ToList();
                dlMyAnnouncements.DataBind();
            }
        }

        protected void btnReadAnnouncemnt_Click(object sender, EventArgs e)
        {

        }
    }
}
